package com.magist.manage.copyrights.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jeesuite.common.util.DateUtils;
import com.magist.core.entity.CxtHolder;
import com.magist.core.entity.Page;
import com.magist.core.entity.ResultMessage;
import com.magist.core.exception.BusinessException;
import com.magist.core.service.SimpleServiceImpl;
import com.magist.core.util.BeanCompareUtil;
import com.magist.core.util.BeanCopyUtil;
import com.magist.core.util.DateUtil;
import com.magist.core.util.MAssertUtil;
import com.magist.core.util.ObjectCheckUtil;
import com.magist.manage.copyrights.dao.SupplyContractMapper;
import com.magist.manage.copyrights.dto.AppendixProjectDto;
import com.magist.manage.copyrights.dto.SupplyContractDto;
import com.magist.manage.copyrights.entity.AppendixProject;
import com.magist.manage.copyrights.entity.ContractBalance;
import com.magist.manage.copyrights.entity.ContractRights;
import com.magist.manage.copyrights.entity.Copyrights;
import com.magist.manage.copyrights.entity.SupplyContract;
import com.magist.manage.copyrights.entity.SupplyInfo;
import com.magist.manage.copyrights.service.AppendixProjectService;
import com.magist.manage.copyrights.service.ContractBalanceService;
import com.magist.manage.copyrights.service.ContractRightsService;
import com.magist.manage.copyrights.service.CopyrightsService;
import com.magist.manage.copyrights.service.SupplyContractService;
import com.magist.manage.copyrights.service.SupplyInfoService;
import com.magist.manage.enums.BalanceTypeEnum;
import com.magist.manage.enums.ContractTypeEnum;
import com.magist.manage.enums.OpActionEnum;
import com.magist.manage.enums.OpTypeEnum;
import com.magist.manage.enums.ValidStatusEnum;
import com.magist.manage.util.BusinessLogUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
public class SupplyContractServiceImpl extends SimpleServiceImpl<SupplyContract> implements SupplyContractService {

    @Autowired
    private SupplyContractMapper supplyContractMapper;
    @Autowired
    private ContractBalanceService contractBalanceService;
    @Autowired
    private AppendixProjectService appendixProjectService;
    @Autowired
    private CopyrightsService copyrightsService;
    @Autowired
    private ContractRightsService contractRightsService;
    @Autowired
    private SupplyInfoService supplyInfoService;
    @Autowired
    private BusinessLogUtil businessLogUtil;

    @Override
    public PageInfo<SupplyContract> page(Example example, Page page) {
        String orderBy = page.getSort() + " " + page.getOrder();
        if (StringUtils.isEmpty(orderBy.trim())) {
            PageHelper.startPage(page.getCurrPage(), page.getLimit());
        } else {
            PageHelper.startPage(page.getCurrPage(), page.getLimit(), orderBy);
        }
        List<SupplyContract> list = this.find(example);
        PageInfo<SupplyContract> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public void addContract(SupplyContractDto supplyContractDto) {
        // 校验参数
        this.check(supplyContractDto);
        // 执行添加合同
        this.doInsertContract(supplyContractDto);
    }

    private void doInsertContract(SupplyContractDto supplyContractDto) {
        // 保存合同
        SupplyContract supplyContract = new SupplyContract();
        BeanUtils.copyProperties(supplyContractDto, supplyContract);
        supplyContract.setId(this.getNewId());
        // 设置合同状态
        supplyContract.setContractStatus(ValidStatusEnum.VALID.getCode());
        this.insert(supplyContract);

        // 保存合同结算
        ContractBalance contractBalance = new ContractBalance();
        BeanUtils.copyProperties(supplyContractDto, contractBalance);
        contractBalance.setId(contractBalanceService.getNewId());
        contractBalance.setContractId(supplyContract.getId());
        contractBalanceService.insert(contractBalance);

        // 保存附件
        List<AppendixProjectDto> appendixProjects = supplyContractDto.getAppendixProjects();
        if (!CollectionUtils.isEmpty(appendixProjects)) {
            appendixProjects.forEach(appendixProject -> {
                if (!StringUtils.isEmpty(appendixProject.getAppendixAddress())) {
                    MAssertUtil.notNull(appendixProject.getAppendixType(), "附件类型为空");
                    MAssertUtil.notNull(appendixProject.getAppendixName(), "附件名称为空");

                    AppendixProject project = new AppendixProject();
                    BeanUtils.copyProperties(appendixProject, project);
                    project.setId(appendixProjectService.getNewId());
                    project.setSupId(supplyContractDto.getSupplyId());
                    project.setProjectId(supplyContract.getId());
                    appendixProjectService.insert(project);
                }
            });
        }

        try {
            String info = BeanCompareUtil.info(BeanCopyUtil.copy(supplyContract, SupplyContractDto.class));
            businessLogUtil.recordBusinessLog(OpActionEnum.ADD.getCode(), OpTypeEnum.SupplyContract.getCode(), supplyContract.getId(), "新增合同:" + supplyContract.getContractNo(), info);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int updateSupplyContract(SupplyContractDto supplyContractDto) {
        // 校验操作
        this.check(supplyContractDto);

        String contractId = supplyContractDto.getId();
        MAssertUtil.notNull(contractId, "供应商合同更新操作主键不能为空");

        // 保存合同
        SupplyContract oldSupplyContract = this.getById(contractId);
        SupplyContractDto oldDto = BeanCopyUtil.copy(oldSupplyContract, SupplyContractDto.class);
        this.fillBalance(oldDto);
        // set三方比例用于比较
        String contractStatus = oldSupplyContract.getContractStatus();
        if (ValidStatusEnum.INVALID.getCode().equals(contractStatus))
            throw new BusinessException("失效合同不允许修改");
        SupplyContract supplyContract = new SupplyContract();
        BeanUtils.copyProperties(supplyContractDto, supplyContract);
        supplyContract.setModifyTime(oldSupplyContract.getModifyTime());

        this.update(supplyContract);

        // 保存合同结算
        ContractBalance contractBalance = contractBalanceService.getByContractId(contractId);
        String balanceId = contractBalance.getId();
        BeanUtils.copyProperties(supplyContractDto, contractBalance);
        contractBalance.setContractId(oldSupplyContract.getId());
        contractBalance.setId(balanceId);

        contractBalanceService.update(contractBalance);

        // 保存附件
        List<AppendixProjectDto> appendixProjects = supplyContractDto.getAppendixProjects();
        List<AppendixProject> contractAppendixs = appendixProjectService.findByProjectId(supplyContract.getId());
        if (!CollectionUtils.isEmpty(appendixProjects)) {
            for (AppendixProjectDto appendixProject : appendixProjects) {
                String appendixId = appendixProject.getId();
                if (StringUtils.isEmpty(appendixId)) {
                    // 新增
                    MAssertUtil.notNull(appendixProject.getAppendixType(), "附件类型为空");
                    MAssertUtil.notNull(appendixProject.getAppendixName(), "附件名称为空");
                    MAssertUtil.notNull(appendixProject.getAppendixAddress(), "附件地址为空");
                    AppendixProject project = new AppendixProject();
                    BeanUtils.copyProperties(appendixProject, project);
                    project.setId(appendixProjectService.getNewId());
                    project.setSupId(supplyContractDto.getSupplyId());
                    project.setProjectId(supplyContract.getId());
                    appendixProjectService.insert(project);
                } else {
                    // 留下要删除的附件
                    for (AppendixProject contractAppendix : contractAppendixs) {
                        String contractAppendixId = contractAppendix.getId();
                        if (contractAppendixId.equals(appendixId)) {
                            contractAppendixs.remove(contractAppendix);
                            break;
                        }
                    }
                    // 更新
                    MAssertUtil.notNull(appendixProject.getAppendixType(), "附件类型为空");
                    MAssertUtil.notNull(appendixProject.getAppendixName(), "附件名称为空");
                    MAssertUtil.notNull(appendixProject.getAppendixAddress(), "附件地址为空");
                    AppendixProject oldProject = appendixProjectService.getById(appendixId);
                    AppendixProject project = new AppendixProject();
                    BeanUtils.copyProperties(appendixProject, project);
                    project.setModifyTime(oldProject.getModifyTime());
                    appendixProjectService.update(project);
                }
            }


        }
        if (!CollectionUtils.isEmpty(contractAppendixs)) {
            // 删除附件
            contractAppendixs.forEach(deleteAppendix -> appendixProjectService.delete(deleteAppendix));

        }

        try {
            String compare = BeanCompareUtil.compare(oldDto, supplyContractDto);
            businessLogUtil.recordBusinessLog(OpActionEnum.EDIT.getCode(), OpTypeEnum.SupplyContract.getCode(), supplyContractDto.getId(), "修改合同:" + supplyContractDto.getContractNo(), compare);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }

    private void fillBalance(SupplyContractDto dto) {
        // 三方比例
        String contractId = dto.getId();
        ContractBalance contractBalance = contractBalanceService.getByContractId(contractId);
        dto.setPartyOne(contractBalance.getPartyOne());
        dto.setPartyThree(contractBalance.getPartyThree());
        dto.setPartyOneNum(contractBalance.getPartyOneNum());
        dto.setPartyTwoNum(contractBalance.getPartyTwoNum());
        dto.setPartyThreeNum(contractBalance.getPartyThreeNum());
        dto.setPartyTwo(contractBalance.getPartyTwo());

        // 附件
        List<AppendixProject> appendixProjects = appendixProjectService.findByProjectId(contractId);

        if (!CollectionUtils.isEmpty(appendixProjects)) {
            List<AppendixProjectDto> copy = BeanCopyUtil.copy(appendixProjects, AppendixProjectDto.class);
            dto.setAppendixProjects(copy);
        }

    }

    private void check(SupplyContractDto supplyContractDto) {
        MAssertUtil.shorterThan(supplyContractDto.getContractName(), 51, "合同名称为空或者超过50个字符");
        MAssertUtil.notNull(supplyContractDto.getContractType(), "合同类型为空");
        // TODO 判断引入合同是否过期
        if (ContractTypeEnum.OUT.getCode().equals(supplyContractDto.getContractType())) {
            String contractInNo = supplyContractDto.getContractInNo();
            MAssertUtil.notNull(contractInNo, "版权输出类型合同的版权引入合同编号不允许为空");
            // 判断有效期(判断该合同剩余有效期是否在6个月以内，如果在6个月以内，该版权即将过期，无法进行版权输出)
            // 1.新增,判断;2.修改无变化,不判断;3.修改改合同,判断.
            String id = supplyContractDto.getId();
            boolean flag = true;
            if (!StringUtils.isEmpty(id)) {
                SupplyContract oldContract = this.getById(id);
                String oldContractInNo = oldContract.getContractInNo();
                if (contractInNo.equals(oldContractInNo)) {
                    flag = false;
                }
            }
            SupplyContract inContract = this.findByContractNo(contractInNo);
            MAssertUtil.notNull(inContract, "版权引入合同不存在");
            // 判断引入合同是否过期
            if (flag) {
                Date inEndDate = inContract.getEndDate();
                Date now = new Date();
                Date date = DateUtil.addMonths(now, 6);
                if (date.after(inEndDate)) {
                    throw new BusinessException("该版权即将过期，无法进行版权输出");
                } else if (now.after(inEndDate)) {
                    throw new BusinessException("该版权已过期，无法进行版权输出");
                }
            }
        }

        MAssertUtil.shorterThan(supplyContractDto.getContractNo(), 21, "合同编号为空或者超过20个字符");
        MAssertUtil.notNull(supplyContractDto.getMounthNum(), "协议有效期为空");
        MAssertUtil.notNull(supplyContractDto.getBeginDate(), "开始时间为空");
        MAssertUtil.notNull(supplyContractDto.getEndDate(), "终止时间为空");
        MAssertUtil.notNull(supplyContractDto.getContractNum(), "签约方数量为空");
        MAssertUtil.notNull(supplyContractDto.getSupplyId(), "合作供应商ID为空");
        MAssertUtil.notNull(supplyContractDto.getLinkMobile(), "联系方式为空");
        MAssertUtil.notNull(supplyContractDto.getSignName(), "签约责编为空");
        MAssertUtil.notNull(supplyContractDto.getCertNo(), "证件号码为空");
        MAssertUtil.notNull(supplyContractDto.getAppendixAddress(), "证件附件为空");
        MAssertUtil.notNull(supplyContractDto.getAccountName(), "账户名为空");
        MAssertUtil.notNull(supplyContractDto.getBankName(), "开户行为空");
        MAssertUtil.notNull(supplyContractDto.getBankNo(), "账号为空");
        MAssertUtil.notNull(supplyContractDto.getBalanceType(), "结算形式为空");
        if (!BalanceTypeEnum.DIVIDE.getCode().equals(supplyContractDto.getBalanceType())) {
            MAssertUtil.notNull(supplyContractDto.getTotalAmount(), "金额为空");
        } else {
            supplyContractDto.setTotalAmount(0D);
        }
        if (!BalanceTypeEnum.BUY.getCode().equals(supplyContractDto.getBalanceType())) {
            MAssertUtil.notNull(supplyContractDto.getPartyOneNum(), "甲方比例为空");
            MAssertUtil.notNull(supplyContractDto.getPartyTwoNum(), "乙方比例为空");
            // 非买断,判断比例总和是否等于100
            Integer partyOneNum = supplyContractDto.getPartyOneNum()==null?0:supplyContractDto.getPartyOneNum();
            Integer partyTwoNum = supplyContractDto.getPartyTwoNum()==null?0:supplyContractDto.getPartyTwoNum();
            Integer partyThreeNum = supplyContractDto.getPartyThreeNum()==null?0:supplyContractDto.getPartyThreeNum();
            Integer balanceTotal = partyOneNum + partyTwoNum + partyThreeNum;
            if (!balanceTotal.equals(100)) {
                throw new BusinessException("比例总和不为100");
            }
        }

        MAssertUtil.notNull(supplyContractDto.getPartyOne(), "甲方名称为空");
        MAssertUtil.notNull(supplyContractDto.getPartyTwo(), "乙方名称为空");

        // 判断是否三方合同
        Integer contractNum = supplyContractDto.getContractNum();
        if (Integer.valueOf(3).equals(contractNum)) {
            MAssertUtil.notNull(supplyContractDto.getPartyThree(), "丙方名称为空");
            MAssertUtil.notNull(supplyContractDto.getPartyThreeNum(), "丙方比例为空");
        }


        // 判断格式是否正确
        MAssertUtil.isNumOrLetterOrChinese(supplyContractDto.getContractName(), "合同名称请填写字母或汉字或数字");
        MAssertUtil.isNormal(supplyContractDto.getContractNo(), "合同编号请填写字母或汉字或数字或\"_\",\"-\"");
        MAssertUtil.isMobile(supplyContractDto.getLinkMobile(), "手机号格式错误");
        MAssertUtil.isNumOrLetter(supplyContractDto.getCertNo(), "营业执照/身份证请填写数字或字母");

        // 判断时间
        if (supplyContractDto.getBeginDate().after(supplyContractDto.getEndDate())) {
            throw new BusinessException("开始时间不能晚于结束时间");
        }

        // 设置supplyName
        String supplyId = supplyContractDto.getSupplyId();
        SupplyInfo supplyInfo = supplyInfoService.getById(supplyId);
        MAssertUtil.notNull(supplyInfo, "供应商不存在");

        supplyContractDto.setSupplyName(supplyInfo.getNickName());
        if (CxtHolder.getUser() != null) {
            supplyContractDto.setModifier(CxtHolder.getUser().getUserName());
        }
        // 查询数据库中是否添加过
        // 判断是否修改
        String id = supplyContractDto.getId();
        if (!StringUtils.isEmpty(id)) {
            SupplyContract oldContract = this.getById(id);
            String oldContractNo = oldContract.getContractNo();
            String oldSupplyId = oldContract.getSupplyId();
            if (oldContractNo.equals(supplyContractDto.getContractNo()) && oldSupplyId.equals(supplyContractDto.getSupplyId())) {
                return;
            }
        }
        SupplyContract supplyContract = this.findByContractNoAndSupply(supplyContractDto.getContractNo(), supplyContractDto.getSupplyId());
        MAssertUtil.isNull(supplyContract, "合同重复添加");

    }

    private SupplyContract findByContractNoAndSupply(String contractNo, String supplyId) {
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setContractNo(contractNo);
        supplyContract.setSupplyId(supplyId);
        List<SupplyContract> supplyContracts = this.find(supplyContract);
        if (!CollectionUtils.isEmpty(supplyContracts)) {
            return supplyContracts.get(0);
        }
        return null;
    }


    @Override
    public SupplyContract findByContractNo(String contractNo) {
        Example example = new Example(SupplyContract.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("contractNo", contractNo);
        criteria.andEqualTo("deleted", "F");
        List<SupplyContract> supplyContracts = find(example);
        if (CollectionUtils.isEmpty(supplyContracts)) {
            return null;
        }
        return supplyContracts.get(0);
    }

    @Override
    public int doInvalidContract(String id) {
        SupplyContract supplyContract = this.getById(id);
        if (supplyContract == null)
            throw new BusinessException("无效的数据!");
        int update = 0;
        if (ValidStatusEnum.VALID.getCode().equals(supplyContract.getContractStatus())) {
            supplyContract.setContractStatus(ValidStatusEnum.INVALID.getCode());
            List<Copyrights> copyrights = copyrightsService.findByContractNoAndStatus(supplyContract.getContractNo(), ValidStatusEnum.VALID.getCode());
            List<ContractRights> contractRights = contractRightsService.findByContractNoAndStatus(supplyContract.getContractNo(), ValidStatusEnum.VALID.getCode());
            // TODO 合同失效，关联的版权和授权也进入失效状态
            copyrightsService.doInvalidByContractId(id);
            contractRightsService.doInvalidByContractId(id);

            try {
                StringBuilder opTitle = new StringBuilder();
                StringBuilder opContent = new StringBuilder();
                if (!CollectionUtils.isEmpty(copyrights)) {
                    opContent.append("关联失效版权:");
                    for (Copyrights copyright : copyrights) {
                        opContent.append(copyright.getCopyrightsNo() + ",");
                    }
                }

                if (!CollectionUtils.isEmpty(contractRights)) {
                    opContent.append("关联失效授权:");
                    for (ContractRights contractRight : contractRights) {
                        opContent.append(contractRight.getContractRightsNo() + ",");
                    }
                }
                businessLogUtil.recordBusinessLog(OpActionEnum.INVALID.getCode(), OpTypeEnum.SupplyContract.getCode(), id, "失效合同:" + supplyContract.getContractNo(), "失效合同:" + supplyContract.getContractNo() + ";状态:[已生效]改成[已失效];" + opContent.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            update = this.update(supplyContract);
        }


        return update;

    }

    @Override
    public void doBatchAdd(List<SupplyContractDto> supplyContractDtos) {
        List<String> supplyAndNo = new LinkedList<String>();
        for (int i = 0; i < supplyContractDtos.size(); i++) {
            SupplyContractDto supplyContractDto = supplyContractDtos.get(i);
            if(ObjectCheckUtil.isAllFieldNull(supplyContractDto)) {
                supplyContractDtos.remove(supplyContractDto);
                i--;
                continue;
            }
            try {
                this.checkImport(supplyContractDto);
                // 合同编号和合作供应商联合为防重复
                String contractNo = supplyContractDto.getContractNo();
                String supplyId = supplyContractDto.getSupplyId();
                String mix = contractNo + supplyId;
                if (supplyAndNo.contains(mix)) {
                    throw new BusinessException("导入数据重复,已存在该合同编号和合作供应商组合的合同");
                } else {
                    supplyAndNo.add(mix);
                }
            } catch (Exception e) {
                throw new BusinessException("第" + (i + 1) + "条数据错误," + e.getMessage());
            }
        }

        businessLogUtil.recordBusinessLog(OpActionEnum.IMPORT.getCode(), OpTypeEnum.ContractRights.getCode(), null, "导入合同开始", "批量导入合同开始,需导入" + supplyContractDtos.size() + "条记录");
        supplyContractDtos.forEach(supplyContractDto -> this.doInsertContract(supplyContractDto));
        businessLogUtil.recordBusinessLog(OpActionEnum.IMPORT.getCode(), OpTypeEnum.ContractRights.getCode(), null, "导入合同结束", "批量导入合同结束,共导入" + supplyContractDtos.size() + "条记录");

    }

    /**
     * 导入时的校验
     *
     * @param supplyContractDto
     */
    private void checkImport(SupplyContractDto supplyContractDto) {
        supplyContractDto.setContractStatus(ValidStatusEnum.VALID.getCode());
        MAssertUtil.shorterThan(supplyContractDto.getContractName(), 51, "合同名称为空或者超过50个字符");
        MAssertUtil.notNull(supplyContractDto.getContractType(), "合同类型为空");
        MAssertUtil.notNull(ContractTypeEnum.getByCode(supplyContractDto.getContractType()), "合同类型填写错误");

        // TODO 判断引入合同是否过期
        if (ContractTypeEnum.OUT.getCode().equals(supplyContractDto.getContractType())) {
            String contractInNo = supplyContractDto.getContractInNo();
            MAssertUtil.notNull(contractInNo, "版权输出类型合同的版权引入合同编号不允许为空");
            // 判断有效期(判断该合同剩余有效期是否在6个月以内，如果在6个月以内，该版权即将过期，无法进行版权输出)
            // 1.新增,判断;2.修改无变化,不判断;3.修改改合同,判断.
            String id = supplyContractDto.getId();
            boolean flag = true;
            if (!StringUtils.isEmpty(id)) {
                SupplyContract oldContract = this.getById(id);
                String oldContractInNo = oldContract.getContractInNo();
                if (contractInNo.equals(oldContractInNo)) {
                    flag = false;
                }
            }
            SupplyContract inContract = this.findByContractNo(contractInNo);
            MAssertUtil.notNull(inContract, "版权引入合同不存在");
            // 判断引入合同是否过期
            if (flag) {
                Date inEndDate = inContract.getEndDate();
                Date now = new Date();
                Date date = DateUtil.addMonths(now, 6);
                if (date.after(inEndDate)) {
                    throw new BusinessException("该版权即将过期，无法进行版权输出");
                } else if (now.after(inEndDate)) {
                    throw new BusinessException("该版权已过期，无法进行版权输出");
                }
            }
        }

        MAssertUtil.shorterThan(supplyContractDto.getContractNo(), 21, "合同编号为空或者超过20个字符");
        MAssertUtil.notNull(supplyContractDto.getMounthNum(), "协议有效期为空");
        MAssertUtil.notNull(supplyContractDto.getBeginDate(), "开始时间为空");
        MAssertUtil.notNull(supplyContractDto.getEndDate(), "终止时间为空");
        MAssertUtil.notNull(supplyContractDto.getContractNum(), "签约方数量为空");
        Integer contractNum = supplyContractDto.getContractNum();
        if (!Integer.valueOf(2).equals(contractNum) && !Integer.valueOf(3).equals(contractNum)) {
            throw new BusinessException("签约方数量填写错误");
        }
        // 导入时合作供应商应由名称查询
        String supplyName = supplyContractDto.getSupplyName();
        MAssertUtil.notNull(supplyName, "合作供应商为空");
        List<SupplyInfo> supplyInfos = supplyInfoService.findByNickName(supplyName);
        MAssertUtil.hasSize(supplyInfos, "查询不到合作供应商");
        if (supplyInfos.size() > 1) {
            throw new BusinessException("该合作供应商查询到多条数据");
        }
        SupplyInfo supplyInfo1 = supplyInfos.get(0);
        String supplyInfo1Id = supplyInfo1.getId();
        supplyContractDto.setSupplyId(supplyInfo1Id);

        MAssertUtil.notNull(supplyContractDto.getLinkMobile(), "联系方式为空");
        MAssertUtil.notNull(supplyContractDto.getSignName(), "签约责编为空");
        MAssertUtil.notNull(supplyContractDto.getCertNo(), "证件号码为空");
//        MAssertUtil.notNull(supplyContractDto.getAppendixAddress(), "证件附件为空");
        MAssertUtil.notNull(supplyContractDto.getAccountName(), "账户名为空");
        MAssertUtil.notNull(supplyContractDto.getBankName(), "开户行为空");
        MAssertUtil.notNull(supplyContractDto.getBankNo(), "账号为空");
        MAssertUtil.notNull(supplyContractDto.getBalanceType(), "结算形式为空");
        MAssertUtil.notNull(BalanceTypeEnum.getByCode(supplyContractDto.getBalanceType()), "结算形式填写错误");
        if (!BalanceTypeEnum.DIVIDE.getCode().equals(supplyContractDto.getBalanceType())) {
            MAssertUtil.notNull(supplyContractDto.getTotalAmount(), "金额为空");
            MAssertUtil.shorterThan(supplyContractDto.getTotalAmount().toString() , 11, "金额输入过长");
        }

        MAssertUtil.notNull(supplyContractDto.getPartyOne(), "甲方名称为空");
        MAssertUtil.notNull(supplyContractDto.getPartyTwo(), "乙方名称为空");

        if (!BalanceTypeEnum.BUY.getCode().equals(supplyContractDto.getBalanceType())) {
            MAssertUtil.notNull(supplyContractDto.getPartyOneNum(), "甲方比例为空");
            MAssertUtil.notNull(supplyContractDto.getPartyTwoNum(), "乙方比例为空");
            MAssertUtil.shorterThan(supplyContractDto.getPartyOne() , 31, "甲方名称过长");
            MAssertUtil.shorterThan(supplyContractDto.getPartyTwo() , 31, "乙方名称过长");
            // 非买断,判断比例总和是否等于100
            Integer partyOneNum = supplyContractDto.getPartyOneNum()==null?0:supplyContractDto.getPartyOneNum();
            Integer partyTwoNum = supplyContractDto.getPartyTwoNum()==null?0:supplyContractDto.getPartyTwoNum();
            Integer partyThreeNum = supplyContractDto.getPartyThreeNum()==null?0:supplyContractDto.getPartyThreeNum();
            Integer balanceTotal = partyOneNum + partyTwoNum + partyThreeNum;
            if (!balanceTotal.equals(100)) {
                throw new BusinessException("比例总和不为100");
            }
        }
        // 判断是否三方合同
        if (Integer.valueOf(3).equals(contractNum)) {
            MAssertUtil.notNull(supplyContractDto.getPartyThree(), "丙方名称为空");
            MAssertUtil.notNull(supplyContractDto.getPartyThreeNum(), "丙方比例为空");
            MAssertUtil.shorterThan(supplyContractDto.getPartyThree() , 31, "丙方名称过长");
        }
        // 判断时间
        if (supplyContractDto.getBeginDate().after(supplyContractDto.getEndDate())) {
            throw new BusinessException("开始时间不能晚于结束时间");
        }
        // 判断格式是否正确
        MAssertUtil.isNumOrLetterOrChinese(supplyContractDto.getContractName(), "合同名称请填写字母或汉字或数字");
        MAssertUtil.isNormal(supplyContractDto.getContractNo(), "合同编号请填写字母或汉字或数字或\"_\",\"-\"");
        MAssertUtil.isMobile(supplyContractDto.getLinkMobile(), "手机号格式错误");
        MAssertUtil.isNumOrLetter(supplyContractDto.getCertNo(), "营业执照/身份证请填写数字或字母");
        // 设置supplyName
        String supplyId = supplyContractDto.getSupplyId();
        SupplyInfo supplyInfo = supplyInfoService.getById(supplyId);
        MAssertUtil.notNull(supplyInfo, "供应商不存在");

        // 长度校验
        MAssertUtil.shorterThan(supplyContractDto.getContractNo(), 21, "合同编号长度超过20个字符");
        MAssertUtil.shorterThan(supplyContractDto.getMounthNum().toString() , 11, "协议有效期过长");
        MAssertUtil.nullOrShorterThan(supplyContractDto.getAddress() , 501, "地址过长");
        MAssertUtil.shorterThan(supplyContractDto.getSignName() , 31, "签约责编输入过长");
        MAssertUtil.shorterThan(supplyContractDto.getCertNo() , 61, "证件号码输入过长");
        MAssertUtil.shorterThan(supplyContractDto.getAccountName() , 61, "账户名过长");
        MAssertUtil.shorterThan(supplyContractDto.getBankName() , 61, "开户行输入过长");
        MAssertUtil.shorterThan(supplyContractDto.getBankNo() , 21, "银行账号输入过长");



        MAssertUtil.nullOrShorterThan(supplyContractDto.getBalanceRemark() , 1001, "结算说明过长");

        supplyContractDto.setSupplyName(supplyInfo.getNickName());
        if (CxtHolder.getUser() != null) {
            supplyContractDto.setModifier(CxtHolder.getUser().getUserName());
        }
        // 查询数据库中是否添加过
        SupplyContract supplyContract = this.findByContractNoAndSupply(supplyContractDto.getContractNo(), supplyContractDto.getSupplyId());
        MAssertUtil.isNull(supplyContract, "合同重复,已存在该合同编号和合作供应商组合的合同");

    }

    @Override
    public int insert(SupplyContract entity) {
        if (CxtHolder.getUser() != null) {
            entity.setModifier(CxtHolder.getUser().getUserName());
        }
        return super.insert(entity);
    }

    @Override
    public int update(SupplyContract entity) {
        if (CxtHolder.getUser() != null) {
            entity.setModifier(CxtHolder.getUser().getUserName());
        }
        return super.update(entity);
    }

    @Override
    public List<SupplyContract> findNearlyExpire(int i) {
        Date dayBegin = DateUtils.getDayBegin(new Date());
        Date endDate = DateUtils.addMonths(dayBegin, i);
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setContractStatus(ValidStatusEnum.VALID.getCode());
        supplyContract.setEndDate(endDate);
        return this.find(supplyContract);
    }

    @Override
    public List<SupplyContract> findByCreateById(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return null;
        }
        SupplyContract supplyContract = new SupplyContract();
        supplyContract.setCreateById(userId);
        return this.find(supplyContract);
    }


    @Override
    public ResultMessage checkContractDate(String contractNo) {
        ResultMessage result = ResultMessage.error();
        SupplyContract inContract = this.findByContractNo(contractNo);
        if (inContract == null) {
            result.setMessage("未查询到合同!");
            return result;
        }
        // 判断是否失效
        if (!ValidStatusEnum.VALID.getCode().equals(inContract.getContractStatus())) {
            result.setMessage("合同已失效!");
            return result;
        }
        Date endDate = inContract.getEndDate();
        Date date = new Date();
        int monthDiff = DateUtil.getMonthDiff(endDate, date);
        if (monthDiff < 6) {
            result.setMessage("该版权即将过期，无法进行版权输出!");
            return result;
        }
        result = ResultMessage.success();
        return result;
    }
}